﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using WindowSwitcher.Behaviors;
using WindowSwitcher.Helper;

namespace WindowSwitcher
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private KeysCollections enableKeys = new KeysCollections();
        private BindingsCollections bindingCollection = new BindingsCollections();
        private Helper.UserActivityHook userActivities = new Helper.UserActivityHook(false, true);

        public KeysCollections EnableKeys
        {
            get { return this.enableKeys; }
            private set
            {
                this.enableKeys = value;
                NotifyPropertyChanged();
            }
        }

        public BindingsCollections BindingsCollection
        {
            get { return this.bindingCollection; }
            private set
            {
                this.bindingCollection = value;
                NotifyPropertyChanged();
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;

            App.Mediator.Register(this);

            userActivities.KeyDown += userActivities_KeyDown;

            this.DofusFilteringCheckBox.Checked += CheckBox_Checked;
            this.DofusFilteringCheckBox.Unchecked += CheckBox_Unchecked;

            CheckBox_Checked(null, null);
        }

        private void userActivities_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            if (bindingCollection.FirstOrDefault(x => x.Key.ToString() == e.KeyData.ToString()) != null)
            {
                var handle = bindingCollection.FirstOrDefault(x => x.Key.ToString() == e.KeyData.ToString()).Handle;
                Helper.NativeMethods.ForceForegroundWindow(handle);
            }
        }

        private void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            this.removeAllItems();

            if (DofusFilteringCheckBox.IsChecked == true)
                this.CheckBox_Checked(null, null);
            else
                this.CheckBox_Unchecked(null, null);
        }

        private void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            removeAllItems();

            var processes = Helper.NativeMethods.GetAllWindows();
            var process = from proc in processes where proc.Process.ProcessName == "Dofus" select proc;

            foreach (var key in process)
            {
                if (key.Title != "")
                {
                    // Set the UI
                    ListboxCustomItem itemUC = new ListboxCustomItem();
                    itemUC.AvatarSource = new BitmapImage(new Uri("pack://application:,,,/WindowSwitcher;component/Images/feca.png"));

                    // Add custom item to the listbox
                    VisualBindings.Items.Add(itemUC);

                    // fill binding collection
                    BindingsCollection.Add(new Behaviors.BindingCollection { HandleName = key.Title, Enabled = true, Handle = key.Handle });
                    NotifyPropertyChanged("BindingsCollection");

                    // Test for update the avatar image (custom item)
                    (VisualBindings.Items.GetItemAt(0) as ListboxCustomItem).setImageSource("feca.png");
                    VisualBindings.InvalidateVisual();
                    NotifyPropertyChanged("VisualBindings");
                }
            }
        }

        private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
        {
            removeAllItems();

            var processes = Helper.NativeMethods.GetAllWindows().Where(x => x.Handle != IntPtr.Zero);     

            foreach(var key in processes)
            {
                if(key.Title != "")
                {
                    // Set the UI
                    ListboxCustomItem itemUC = new ListboxCustomItem();
                    VisualBindings.Items.Add(itemUC);
                    BindingsCollection.Add(new Behaviors.BindingCollection { HandleName = key.Title, Enabled = true, Handle = key.Handle });
                    NotifyPropertyChanged("BindingsCollection");
                }
            }
        }

        private void removeAllItems()
        {
            int i = 0;

            while (i < this.BindingsCollection.Count)
            {
                this.BindingsCollection.RemoveAt(i);
                VisualBindings.Items.RemoveAt(i);
            }

            this.EnableKeys.Reset();
        }
    }
}
